//
//  AccountLoginViewController.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/8.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "AccountLoginViewController.h"
#import <MBProgressHUD.h>
#import "VervifyPhone.h"
#import "LoginNet.h"
#import "ResetPasswordViewController.h"
#import "RegisterViewController.h"
#import "BLHeader.h"
#import <Masonry.h>
#import "HomeViewController.h"
#import "BLNavigationController.h"

@interface AccountLoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UITextField *telFeild;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UILabel *missWord;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UILabel *codeLabel;
@property (weak, nonatomic) IBOutlet UIButton *pwdLoginBtn;//选择密码登录按钮
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (nonatomic, assign) BOOL isCodeLogin;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSUInteger time;

@end

@implementation AccountLoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController.navigationBar setHidden:NO];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.title = @"账号登录";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.isCodeLogin = NO;
    
    UIBarButtonItem *rightRegister = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(toRegister)];
   
    [rightRegister setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:kAppThemeColor ,NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = rightRegister;

    __weak typeof (self) weakSelf = self;
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 1.5));
        make.top.equalTo(weakSelf.pwdLoginBtn.mas_bottom).with.offset(5);
        make.centerX.equalTo(weakSelf.pwdLoginBtn.mas_centerX);
    }];
    
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"忘记密码?"];
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, 5)];
    self.missWord.attributedText = str;
    self.contentView.layer.cornerRadius = 5;
    [self.telFeild becomeFirstResponder];
    
    
    UITapGestureRecognizer *hide = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [self.view addGestureRecognizer:hide];
    
    self.missWord.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toResetPWD)];
    [self.missWord addGestureRecognizer:tap];
    
    self.codeBtn.layer.cornerRadius = 5;
    self.loginBtn.layer.cornerRadius = 5;
    
}

- (void)toRegister {
    RegisterViewController *registerController = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerController animated:YES];
}

- (void)toResetPWD {
    ResetPasswordViewController *resetController = [[ResetPasswordViewController alloc] init];
    [self.navigationController pushViewController:resetController animated:YES];
}


- (void)hideKeyboard {
    [self.view endEditing:YES];

}


# pragma mark 登录
- (IBAction)login:(id)sender {
    NSString *tel = self.telFeild.text;
    NSString *pwd = self.passwordField.text;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    
    if ([tel isEqualToString:@""])
    {
        hud.label.text = @"请输入注册手机号码";
        [hud hideAnimated:YES afterDelay:4];
        return;
    }
    if (tel.length != 11 || ![VervifyPhone vervifyTellphoneNumber:tel])
    {
        [hud hideAnimated:YES afterDelay:4];
        hud.label.text = @"手机号码格式不正确";
        return;
    }
    if ([pwd isEqualToString:@""])
    {
        [hud hideAnimated:YES afterDelay:4];
        hud.label.text = @"请输入密码";
        return;
    }
    if (pwd.length < 6)
    {
        [hud hideAnimated:YES afterDelay:4];
        hud.label.text = @"密码长度至少六位";
        return;
    }
    if (pwd.length > 20)
    {
        [hud hideAnimated:YES afterDelay:4];
        hud.label.text = @"您输入的密码过长";
        return;
    }
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.label.text = @"拼命加载中。。。";
    __weak typeof (self) weakSelf = self;
    [LoginNet postWithTel:tel password:pwd loginType:self.isCodeLogin completer:^(id resultObjec, NSError *error) {
        if(error) {
            hud.mode = MBProgressHUDModeText;
            [hud hideAnimated:YES afterDelay:3];
            hud.label.text = [error localizedDescription];
            return;
        }
        
        [hud hideAnimated:YES];
        // 登录成功 跳转到主页
        
        [weakSelf presentViewController:[[BLNavigationController alloc] initWithRootViewController:[[HomeViewController alloc] init]] animated:YES completion:nil];
        [[NSUserDefaults standardUserDefaults] setObject:Logined forKey:Logined];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
    
}

- (IBAction)getCode:(UIButton *)sender {
    if(self.time > 0) {
        return;
    }
    
    NSString *tel = self.telFeild.text;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    if ([tel isEqualToString:@""]) {
        hud.label.text = @"请输入注册手机号码";
        [hud hideAnimated:YES afterDelay:3];
        return;
    }
    
    if (tel.length != 11 || ![VervifyPhone vervifyTellphoneNumber:tel]) {
        [hud hideAnimated:YES afterDelay:3];
        hud.label.text = @"手机号码格式不正确";
        return;
    }
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.label.text = @"拼命加载中。。。";
    [LoginNet getCodeWithTel:tel codeType:2 completer:^(id resultObject, NSError *error) {
        if(error) {
            hud.mode = MBProgressHUDModeText;
            [hud hideAnimated:YES afterDelay:3];
            hud.label.text = [error localizedDescription];
            return;
        }
        [hud hideAnimated:YES];
    }];
    self.time = 120;
    sender.userInteractionEnabled = NO;
    __weak typeof (self) weakSelf = self;
    [sender setTitle:@"120s后重新获取" forState:UIControlStateNormal];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        weakSelf.time--;
        if(weakSelf.time == 0) {
            [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
            sender.userInteractionEnabled = YES;
            [weakSelf.timer invalidate];
        }else {
            [sender setTitle:[NSString stringWithFormat:@"%zis后重新获取",weakSelf.time] forState:UIControlStateNormal];
        }

    }];

    
}

#pragma mark 选择密码登录
- (IBAction)passwordLogin:(UIButton *)sender {
    if(!_isCodeLogin) {
        return;
    }
    self.passwordField.keyboardType = UIKeyboardTypeDefault;
    self.passwordField.secureTextEntry = YES;
    
    __weak typeof (self) weakSelf = self;
    [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 1.5));
        make.top.equalTo(sender.mas_bottom).with.offset(5);
        make.centerX.equalTo(sender.mas_centerX);
    }];
    [UIView animateWithDuration:0.3 animations:^{
         [weakSelf.view layoutIfNeeded];

    }];
    self.passwordField.placeholder = @"请输入密码";
    self.passwordField.text = @"";
    self.codeLabel.text = @"您的密码:";
    self.codeBtn.hidden = YES;
    self.isCodeLogin = NO;

}

#pragma mark 选择验证码登录
- (IBAction)codeLogin:(UIButton *)sender {
    if(_isCodeLogin) {
        return;
    }
     __weak typeof (self) weakSelf = self;
    [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 1.5));
        make.top.equalTo(sender.mas_bottom).with.offset(5);
        make.centerX.equalTo(sender.mas_centerX);
    }];

    [UIView animateWithDuration:0.3 animations:^{
        [weakSelf.view layoutIfNeeded];
    }];
    self.passwordField.keyboardType = UIKeyboardTypeNumberPad;
    self.passwordField.secureTextEntry = NO;
    self.passwordField.placeholder = @"请输入验证码";
    self.passwordField.text = @"";
    self.codeLabel.text = @"验 证 码:";
    self.codeBtn.hidden = NO;
    self.isCodeLogin = YES;
}


@end
